<template>
  <div class="price-comparison-container">
    <!-- 搜索区域 -->
    <el-form
      ref="searchFormRef"
      :model="searchForm"
      inline
      label-width="80px"
      class="mb-4 p-4 bg-gray-50 rounded-lg shadow-sm"
    >
      <el-form-item label="商品名称">
        <el-input
          v-model="searchForm.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item label="供应商">
        <el-select
          v-model="searchForm.supplier"
          placeholder="请选择供应商"
          filterable
          remote
          :remote-method="remoteMethod"
          :loading="loading"
        >
          <el-option
            v-for="item in supplierOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态">
          <el-option label="全部" value=""></el-option>
          <el-option label="待比价" value="pending"></el-option>
          <el-option label="已比价" value="completed"></el-option>
          <el-option label="已下单" value="ordered"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 比价单表格 -->
    <div class="table-container p-4 bg-white rounded-lg shadow-sm">
      <el-table
        :data="comparisonData"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{
          backgroundColor: '#f5f7fa',
          color: '#606266',
          fontWeight: 'bold',
        }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="60" align="center">
          <template #header>
            <span class="text-sm">选择</span>
          </template>
        </el-table-column>
        <el-table-column prop="companyName" label="供应商名称" width="160">
          <template #default="scope">
            <div class="flex items-center">
              <el-avatar
                size="mini"
                :src="scope.row.logoUrl"
                :alt="scope.row.companyName"
              />
              <span class="ml-2 text-sm">{{ scope.row.companyName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="inquiryId"
          label="询价单ID"
          width="120"
          align="center"
        />
        <el-table-column
          prop="taxIncludedPrice"
          label="含税单价"
          width="100"
          align="right"
        >
          <template #default="scope">
            <span class="text-sm font-medium"
              >¥{{ scope.row.taxIncludedPrice.toFixed(2) }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="discountedTaxIncludedPrice"
          label="折后含税单价"
          width="120"
          align="right"
        >
          <template #default="scope">
            <span class="text-sm font-medium text-primary"
              >¥{{ scope.row.discountedTaxIncludedPrice.toFixed(2) }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="discountRate"
          label="折扣率"
          width="90"
          align="center"
        >
          <template #default="scope">
            <span class="text-sm"
              >{{ (scope.row.discountRate * 100).toFixed(1) }}%</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="discountType"
          label="折扣类型"
          width="100"
          align="center"
        >
          <template #default="scope">
            <el-tag
              :type="scope.row.discountType === 'percent' ? 'success' : 'info'"
            >
              {{ scope.row.discountType === "percent" ? "百分比" : "固定金额" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="discountAmount"
          label="折扣额"
          width="100"
          align="right"
        >
          <template #default="scope">
            <span class="text-sm"
              >-¥{{ scope.row.discountAmount.toFixed(2) }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="discountedPrice"
          label="折后单价"
          width="100"
          align="right"
        >
          <template #default="scope">
            <span class="text-sm"
              >¥{{ scope.row.discountedPrice.toFixed(2) }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="taxRate" label="税率" width="80" align="center">
          <template #default="scope">
            <span class="text-sm"
              >{{ (scope.row.taxRate * 100).toFixed(0) }}%</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="taxAmount"
          label="税额"
          width="100"
          align="right"
        >
          <template #default="scope">
            <span class="text-sm">¥{{ scope.row.taxAmount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="totalPriceWithTax"
          label="价税合计"
          width="120"
          align="right"
        >
          <template #default="scope">
            <span class="text-sm font-medium text-danger"
              >¥{{ scope.row.totalPriceWithTax.toFixed(2) }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="purchaseFee"
          label="采购费用"
          width="100"
          align="right"
        >
          <template #default="scope">
            <span class="text-sm">¥{{ scope.row.purchaseFee.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="orderNo"
          label="订单编号"
          width="120"
          align="center"
        />
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="viewDetails(scope.row)"
              class="text-primary hover:underline"
            >
              <el-icon><Document /></el-icon>查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 合计行 -->
      <div
        class="mt-4 p-3 bg-gray-50 rounded flex justify-between items-center"
      >
        <div class="flex items-center">
          <el-checkbox v-model="allSelected" @change="handleSelectAll"
            >全选</el-checkbox
          >
          <span class="ml-4 text-sm text-gray-600"
            >已选择
            <span class="font-medium text-primary">{{ selectedCount }}</span>
            家供应商</span
          >
        </div>
        <div class="text-right">
          <div class="text-sm text-gray-600">
            最低含税单价：<span class="font-medium text-danger ml-2"
              >¥{{ minTaxIncludedPrice.toFixed(2) }}</span
            >
          </div>
          <div class="text-sm text-gray-600">
            最低折后价：<span class="font-medium text-danger ml-2"
              >¥{{ minDiscountedPrice.toFixed(2) }}</span
            >
          </div>
          <div class="text-sm text-gray-600">
            预计总金额：<span class="font-medium text-danger ml-2"
              >¥{{ totalAmount.toFixed(2) }}</span
            >
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="mt-6 flex justify-end gap-3">
        <el-button type="primary" @click="createPurchaseOrder">
          <el-icon><ShoppingCart /></el-icon>生成采购单
        </el-button>
        <el-button type="success" @click="compareAgain">
          <el-icon><Refresh /></el-icon>重新比价
        </el-button>
        <el-button type="info" @click="exportComparison">
          <el-icon><Download /></el-icon>导出比价单
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick } from "vue";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElButton,
  ElTable,
  ElTableColumn,
  ElTag,
  ElAvatar,
  ElCheckbox,
  ElMessage,
  ElIcon,
} from "element-plus";
import {
  Search,
  Refresh,
  Document,
  ShoppingCart,
  Download,
} from "@element-plus/icons-vue";

// 搜索表单
const searchFormRef = ref(null);
const searchForm = reactive({
  productName: "笔记本电脑",
  supplier: "",
  status: "",
});

// 供应商搜索
const supplierOptions = ref([]);
const loading = ref(false);
const remoteMethod = (query) => {
  if (query) {
    loading.value = true;
    setTimeout(() => {
      supplierOptions.value = [
        { value: "supplier1", label: "京东数码" },
        { value: "supplier2", label: "苏宁易购" },
        { value: "supplier3", label: "天猫电子" },
        { value: "supplier4", label: "中关村科技" },
        { value: "supplier5", label: "华强北数码" },
      ].filter((item) =>
        item.label.toLowerCase().includes(query.toLowerCase())
      );
      loading.value = false;
    }, 200);
  } else {
    supplierOptions.value = [];
  }
};

// 表格数据
const comparisonData = ref([
  {
    id: 1,
    companyName: "京东数码",
    logoUrl: "https://picsum.photos/id/1/40/40",
    inquiryId: "XJ-20250625-001",
    taxIncludedPrice: 5999.0,
    discountedTaxIncludedPrice: 5499.0,
    discountRate: 0.083,
    discountType: "percent",
    discountAmount: 500.0,
    discountedPrice: 4866.37,
    taxRate: 0.13,
    taxAmount: 632.63,
    totalPriceWithTax: 5499.0,
    purchaseFee: 0.0,
    orderNo: "ORD-20250625-001",
    selected: false,
  },
  {
    id: 2,
    companyName: "苏宁易购",
    logoUrl: "https://picsum.photos/id/2/40/40",
    inquiryId: "XJ-20250625-002",
    taxIncludedPrice: 6199.0,
    discountedTaxIncludedPrice: 5599.0,
    discountRate: 0.097,
    discountType: "percent",
    discountAmount: 600.0,
    discountedPrice: 4954.87,
    taxRate: 0.13,
    taxAmount: 644.13,
    totalPriceWithTax: 5599.0,
    purchaseFee: 15.0,
    orderNo: "ORD-20250625-002",
    selected: false,
  },
  {
    id: 3,
    companyName: "天猫电子",
    logoUrl: "https://picsum.photos/id/3/40/40",
    inquiryId: "XJ-20250625-003",
    taxIncludedPrice: 6299.0,
    discountedTaxIncludedPrice: 5299.0,
    discountRate: 0.159,
    discountType: "percent",
    discountAmount: 1000.0,
    discountedPrice: 4689.38,
    taxRate: 0.13,
    taxAmount: 609.62,
    totalPriceWithTax: 5299.0,
    purchaseFee: 10.0,
    orderNo: "ORD-20250625-003",
    selected: false,
  },
  {
    id: 4,
    companyName: "中关村科技",
    logoUrl: "https://picsum.photos/id/4/40/40",
    inquiryId: "XJ-20250625-004",
    taxIncludedPrice: 6099.0,
    discountedTaxIncludedPrice: 5699.0,
    discountRate: 0.066,
    discountType: "percent",
    discountAmount: 400.0,
    discountedPrice: 5043.36,
    taxRate: 0.13,
    taxAmount: 655.64,
    totalPriceWithTax: 5699.0,
    purchaseFee: 0.0,
    orderNo: "ORD-20250625-004",
    selected: false,
  },
  {
    id: 5,
    companyName: "华强北数码",
    logoUrl: "https://picsum.photos/id/5/40/40",
    inquiryId: "XJ-20250625-005",
    taxIncludedPrice: 5899.0,
    discountedTaxIncludedPrice: 5399.0,
    discountRate: 0.085,
    discountType: "percent",
    discountAmount: 500.0,
    discountedPrice: 4777.88,
    taxRate: 0.13,
    taxAmount: 621.12,
    totalPriceWithTax: 5399.0,
    purchaseFee: 20.0,
    orderNo: "ORD-20250625-005",
    selected: false,
  },
]);

// 单选控制
const selectedRow = ref(null);
const handleSelectionChange = (rows) => {
  if (rows.length > 0) {
    // 单选控制：只保留最后选择的一项
    const latestRow = rows[rows.length - 1];
    selectedRow.value = latestRow;
    comparisonData.value.forEach((item) => {
      item.selected = item.id === latestRow.id;
    });
  } else {
    selectedRow.value = null;
    comparisonData.value.forEach((item) => {
      item.selected = false;
    });
  }
};

// 全选控制
const allSelected = ref(false);
const handleSelectAll = (val) => {
  if (val) {
    // 单选模式下不支持全选
    allSelected.value = false;
    ElMessage.warning("比价单只允许选择一家供应商");
  } else {
    selectedRow.value = null;
  }
};

// 计算属性
const selectedCount = computed(() => {
  return comparisonData.value.filter((item) => item.selected).length;
});

const minTaxIncludedPrice = computed(() => {
  if (comparisonData.value.length === 0) return 0;
  return Math.min(...comparisonData.value.map((item) => item.taxIncludedPrice));
});

const minDiscountedPrice = computed(() => {
  if (comparisonData.value.length === 0) return 0;
  return Math.min(
    ...comparisonData.value.map((item) => item.discountedTaxIncludedPrice)
  );
});

const totalAmount = computed(() => {
  if (!selectedRow.value) return 0;
  return selectedRow.value.totalPriceWithTax + selectedRow.value.purchaseFee;
});

// 搜索方法
const handleSearch = () => {
  console.log("搜索条件：", searchForm);
  // 这里可以添加实际的搜索逻辑
};

// 重置方法
const handleReset = () => {
  searchFormRef.value.resetFields();
  searchForm.productName = "";
  searchForm.supplier = "";
  searchForm.status = "";
};

// 操作方法
const viewDetails = (row) => {
  console.log("查看详情：", row);
  ElMessage.info(`查看 ${row.companyName} 的报价详情`);
};

const createPurchaseOrder = () => {
  if (!selectedRow.value) {
    ElMessage.warning("请先选择一家供应商");
    return;
  }
  console.log("生成采购单：", selectedRow.value);
  ElMessage.success(
    `已选择 ${selectedRow.value.companyName}，正在生成采购单...`
  );
};

const compareAgain = () => {
  console.log("重新比价");
  ElMessage.info("正在获取最新报价...");
};

const exportComparison = () => {
  console.log("导出比价单");
  ElMessage.success("比价单导出成功");
};

// 初始化选中最低价
nextTick(() => {
  if (comparisonData.value.length > 0) {
    const lowestPriceRow = comparisonData.value.reduce((prev, current) =>
      prev.discountedTaxIncludedPrice < current.discountedTaxIncludedPrice
        ? prev
        : current
    );
    lowestPriceRow.selected = true;
    selectedRow.value = lowestPriceRow;
  }
});
</script>

<style scoped>
.price-comparison-container {
  padding: 24px;
  max-width: 1600px;
  margin: 0 auto;
}

.table-container {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.text-primary {
  color: #409eff;
}

.text-danger {
  color: #f56c6c;
}

.text-sm {
  font-size: 13px;
}

.font-medium {
  font-weight: 500;
}

.bg-gray-50 {
  background-color: #f9fafb;
}

.hover\\:underline:hover {
  text-decoration: underline;
}
</style>